# 主程序入口（严格按结构）
from database.db_manager import init_db
from reminder.reminder_service import run_reminder_service
from gui.main_window import start_gui
import threading
import socket

def start_tcp_server():
    """启动TCP服务器（用于接收提醒事件）"""
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('0.0.0.0', 8080))
    server_socket.listen(5)
    print("[TCP] Server started on port 8080")
    
    while True:
        client_socket, addr = server_socket.accept()
        print(f"[TCP] Connection from {addr}")
        data = client_socket.recv(1024).decode('utf-8')
        print(f"[TCP] Received: {data}")
        client_socket.close()

if __name__ == "__main__":
    # 初始化数据库
    init_db()
    
    # 启动后台提醒服务
    reminder_thread = threading.Thread(
        target=run_reminder_service,
        daemon=True
    )
    reminder_thread.start()
    
    # 启动TCP服务器
    tcp_thread = threading.Thread(
        target=start_tcp_server,
        daemon=True
    )
    tcp_thread.start()
    
    # 启动GUI
    start_gui()
    
    print("\n[SYSTEM] ✅ All services running:")
    print("  - Database initialized")
    print("  - Reminder service (daemon) running")
    print("  - TCP server (port 8080) running")
    print("  - GUI interface started")
    print("  - Ready for user input (type 'exit' to quit)\n")
    
    # 保持主程序运行
    while True:
        try:
            cmd = input(">>> ")
            if cmd.lower() == "exit":
                break
        except KeyboardInterrupt:
            break